package com.example.demo.sort;

import java.util.Arrays;

/**
 * 归并排序
 * <p>
 * 时间复杂度：O(n*log(n))<br>
 * 空间复杂度：O(n)
 *
 * @author WangYX
 * @version 1.0.0
 * @date 2024/03/08 10:28
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 5, 6, 7, 2, 4, 7, 1, 34, 5, 6};
        int[] ints = mergeSort(arr);
        System.out.println(Arrays.toString(ints));
    }

    /**
     * 2路归并算法
     *
     * @param array 数组
     * @return {@link int[]}
     * @author WangYX
     * @date 2024/03/08 10:29
     */
    public static int[] mergeSort(int[] array) {
        if (array.length < 2) {
            return array;
        }
        int mid = array.length / 2;
        int[] left = Arrays.copyOfRange(array, 0, mid);
        int[] right = Arrays.copyOfRange(array, mid, array.length);
        return merge(mergeSort(left), mergeSort(right));
    }

    public static int[] merge(int[] left, int[] right) {
        int[] result = new int[left.length + right.length];
        for (int index = 0, i = 0, j = 0; index < result.length; index++) {
            if (i >= left.length) {
                result[index] = right[j++];
            } else if (j >= right.length) {
                result[index] = left[i++];
            } else if (left[i] > right[j]) {
                result[index] = right[j++];
            } else {
                result[index] = left[i++];
            }
        }
        return result;
    }
}
